/*
 * Copyright (c) 2010, Nikolaus Moll
 * All rights reserved.
 */
package net.miblounge.gradecalculator.core;

import java.io.File;
import java.io.FileFilter;
import java.util.HashMap;

import net.miblounge.gradecalculator.grade.IGradeFactory;
import net.miblounge.gradecalculator.plugin.exceptions.PluginException;
import net.miblounge.gradecalculator.plugin.loader.PluginLoader;

public final class GradeFactoryUtil {
	private static GradeFactoryUtil instance = null;
	private static String pluginsRoot = "plugins/grades/";
	private final HashMap<String, IGradeFactory> factories;
	private final HashMap<String, File> pluginMap;
	
	private GradeFactoryUtil()
	{
		factories = new HashMap<String, IGradeFactory>();

		pluginMap = new HashMap<String, File>();

		final File root = new File(pluginsRoot);
		final File[] plugins = root.listFiles(new FileFilter() {
			@Override
			public boolean accept(final File pathname) {
				if (pathname.isDirectory()) {
					return false;
				}
				return pathname.getAbsolutePath().endsWith(".jar");
			}
		});

		final String resource = "importplugin";
		for (File plugin : plugins) {
			try {
				final IGradeFactory factory = (IGradeFactory)PluginLoader.getPluginByResource(plugin, resource);
				pluginMap.put(factory.getCountryCode(), plugin);
				//CHECKSTYLE:OFF
			} catch (final PluginException e) {
				// do something...
				//CHECKSTYLE:ON
			}
		}
	}
	
	public static GradeFactoryUtil getInstance()
	{
		if (instance == null) {
			instance = new GradeFactoryUtil();
		}
		
		return instance;
	}
	
	public static void setPluginsRoot(final String root)
	{
		pluginsRoot = root;
		instance = null;
	}
	
	public IGradeFactory getFab(final String cc)
	{
		if (!factories.containsKey(cc)) {
			factories.put(cc, getPlugin(cc));
		}
		
		return factories.get(cc);
	}
	
	public void registerFactory(final IGradeFactory fab)
	{
		if (factories.containsKey(fab.getCountryCode())) {
			factories.remove(fab.getCountryCode());
		}
		
		factories.put(fab.getCountryCode(), fab);
	}

	private IGradeFactory getPlugin(final String cc)
	{
		if (!pluginMap.containsKey(cc)) {
			throw new PluginException("No Plugin for Country Code " + cc);
		}
		
		final String resource = "importplugin";
		return (IGradeFactory)PluginLoader.getPluginByResource(pluginMap.get(cc), resource);
	}

	public boolean hasFactory(final String countryCode) {
		try {
			return getFab(countryCode) != null;
		} catch (final PluginException e) {
			return false;
		}
	}
}
